package com.smedi.ismedi.dangeroussourcemanage.core.port.adapter.persistence.repository.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.ObjectUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.IService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.smedi.ismedi.authority.starter.util.AuthorityUtil;
import com.smedi.ismedi.authority.starter.util.VerifyHelper;
import com.smedi.ismedi.constructionproject.api.dto.response.ProjectBasicResponse;
import com.smedi.ismedi.dangeroussourcemanage.api.dto.request.DangerSourceListRequest;
import com.smedi.ismedi.dangeroussourcemanage.api.dto.request.DangerSourceTimeLineRequest;
import com.smedi.ismedi.dangeroussourcemanage.core.domain.aggregatemodel.*;
import com.smedi.ismedi.dangeroussourcemanage.core.domain.repository.DangerousSourceLibraryRepository;
import com.smedi.ismedi.dangeroussourcemanage.core.domain.repository.DangerousSourceManageRepository;
import com.smedi.ismedi.dangeroussourcemanage.core.port.adapter.persistence.model.DangerousSourceManageEntity;
import com.smedi.ismedi.dangeroussourcemanage.core.port.adapter.persistence.mybatis.mapper.DangerousSourceManageMapper;
import com.smedi.ismedi.dangeroussourcemanage.core.port.adapter.service.ConstructionProjectRemoteApiService;
import com.smedi.ismedi.web.starter.util.DozerUtil;
import lombok.AllArgsConstructor;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

import static com.smedi.ismedi.dangeroussourcemanage.core.infrastructure.constant.ConstantField.ACCESS_PROJECT;

/**
 * 基础信息仓库实现类
 *
 * @author xienannan
 * @date 2021/08/23
 */
@Repository
@AllArgsConstructor
public class DangerousSourceManageRepositoryImpl extends ServiceImpl<DangerousSourceManageMapper, DangerousSourceManageEntity> implements DangerousSourceManageRepository, IService<DangerousSourceManageEntity> {
    private final DangerousSourceManageMapper dangerousSourceManageMapper;
    private final DangerousSourceLibraryRepository dangerousSourceLibraryRepository;
    private final ConstructionProjectRemoteApiService constructionProjectRemoteApiService;
    private final AuthorityUtil authorityUtil;
    private final DozerUtil dozerUtil;

    @Override
    public DangerousSourceManage doSelectById(Long dangerousSourceId) {
        DangerousSourceManageEntity dangerousSourceManageEntity = dangerousSourceManageMapper.selectById(dangerousSourceId);
        if (dangerousSourceManageEntity == null) {
            return null;
        }
        ProjectBasicResponse projectBasicResponse = constructionProjectRemoteApiService.queryProjectBasicView(dangerousSourceManageEntity.getProjectId());
        DangerousSourceManage dangerousSourceManage = dozerUtil.convertor(dangerousSourceManageEntity, DangerousSourceManage.class);
        if (projectBasicResponse != null) {
            dangerousSourceManage.setProjectManager(projectBasicResponse.getProjectManager());
            dangerousSourceManage.setMobile(projectBasicResponse.getMobile());
            dangerousSourceManage.setProjectAddress(projectBasicResponse.getProjectAddress());
        }

        LocalDateTime nowDate = LocalDateTime.now();
        if (dangerousSourceManage.getLibraryId() > 0) {
            if (dangerousSourceManage.getLibraryId() > 0) {
                DangerousSourceLibrary dangerousSourceLibrary = dangerousSourceLibraryRepository.selectDangerousSourceLibraryById(dangerousSourceManage.getLibraryId());
                dangerousSourceManage.setDangerousSourceLibrary(dangerousSourceLibrary);
            }

            //判断是不是同一天
            LocalDateTime startTime = dangerousSourceManage.getPlanConstructionTime();
            LocalDateTime endTime = dangerousSourceManage.getPlanEndTime();

            if (nowDate.getDayOfMonth() == dangerousSourceManage.getPlanConstructionTime().getDayOfMonth()) {
                startTime.plusDays(1);
            }
            if (nowDate.getDayOfMonth() == dangerousSourceManage.getPlanEndTime().getDayOfMonth()) {
                endTime.plusDays(1);
            }

//            if (nowDate.isBefore(startTime)) {
//                dangerousSourceManage.setConstructionStatus("-1");
//            } else if (nowDate.isAfter(startTime) && nowDate.isBefore(endTime)) {
//                dangerousSourceManage.setConstructionStatus("0");
//            } else if (nowDate.isAfter(endTime)) {
//                dangerousSourceManage.setConstructionStatus("1");
//            }

            if (nowDate.isBefore(startTime)) {
                dangerousSourceManage.setConstructionStatus("-1");
            }
            if (!nowDate.isBefore(startTime)&&!nowDate.isAfter(endTime.plusDays(1))) {
                dangerousSourceManage.setConstructionStatus("0");
            }
            if(nowDate.isAfter(endTime.plusDays(1))) {
                dangerousSourceManage.setConstructionStatus("1");
            }
        }

        return dangerousSourceManage;
    }

    @Override
    public Page<DangerousSourceManage> selectDangerousSourcePageList(QueryDangerousSourceManagePageList queryDangerousSourceManagePageList) {
        Page<DangerousSourceManageEntity> dangerousSourceManagePage = new Page<>(queryDangerousSourceManagePageList.getPageNum(), queryDangerousSourceManagePageList.getPageSize());
        Page<DangerousSourceManage> dangerousSourceManagePageReturn = new Page<>();
        QueryWrapper<DangerousSourceManageEntity> wrapper = new QueryWrapper<>();
        dangerousSourceManagePage.addOrder(OrderItem.desc("id"));

        if (queryDangerousSourceManagePageList.getProjectIds() != null && queryDangerousSourceManagePageList.getProjectIds().size() > 0) {
            wrapper.in("project_id", queryDangerousSourceManagePageList.getProjectIds());
        }else{
            return dangerousSourceManagePageReturn;
        }
        if (queryDangerousSourceManagePageList.getConstructionUnit() != null && queryDangerousSourceManagePageList.getConstructionUnit().length() > 0) {
            wrapper.like("construction_unit", queryDangerousSourceManagePageList.getConstructionUnit());
        }

        if (queryDangerousSourceManagePageList.getEngineeringCategory() != null && queryDangerousSourceManagePageList.getEngineeringCategory().length() > 0) {
            List<Long> longList = dangerousSourceLibraryRepository.selectDangerousSourceLibraryByEngineeringCategory(queryDangerousSourceManagePageList.getEngineeringCategory());
            wrapper.in("library_id", longList);
        }
        if (queryDangerousSourceManagePageList.getUnitEngineering() != null && queryDangerousSourceManagePageList.getUnitEngineering().length() > 0) {
            wrapper.like("unit_engineering", queryDangerousSourceManagePageList.getUnitEngineering());
        }
        //开始时间段
        if (queryDangerousSourceManagePageList.getPlanConstructionTime() != null && queryDangerousSourceManagePageList.getPlanConstructionTime().length() > 0) {
            String[] strArr = queryDangerousSourceManagePageList.getPlanConstructionTime().split(",");
            LocalDateTime startTime0 = LocalDateTime.parse(strArr[0].toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime startTime1 = LocalDateTime.parse(strArr[1].toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            wrapper.between("plan_construction_time", startTime0, startTime1);
        }
        //结束时间段
        if (queryDangerousSourceManagePageList.getPlanEndTime() != null && queryDangerousSourceManagePageList.getPlanEndTime().length() > 0) {
            String[] strArr = queryDangerousSourceManagePageList.getPlanEndTime().split(",");
            LocalDateTime startTime0 = LocalDateTime.parse(strArr[0], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime startTime1 = LocalDateTime.parse(strArr[1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            wrapper.between("plan_end_time", startTime0, startTime1);
        }
        if (queryDangerousSourceManagePageList.getKeyHazards() != null && queryDangerousSourceManagePageList.getKeyHazards().length() > 0) {
            List<Long> longList = dangerousSourceLibraryRepository.selectDangerousSourceLibraryByKeyHazards(queryDangerousSourceManagePageList.getKeyHazards());
            if (longList.size() > 0) {
                wrapper.in("library_id", longList);
            }
        }
        if (queryDangerousSourceManagePageList.getConstructionStatus() != null && queryDangerousSourceManagePageList.getConstructionStatus().length() > 0) {
            LocalDate nowDate = LocalDate.now();
            switch (queryDangerousSourceManagePageList.getConstructionStatus()) {
                case "-1":
                    wrapper.ge("plan_construction_time", nowDate);
                    break;
                case "0":
                    wrapper.le("plan_construction_time", nowDate);
                    wrapper.ge("plan_end_time", nowDate);
                    break;
                case "1":
                    wrapper.le("plan_end_time", nowDate);
                    break;
                default:
                    break;
            }
        }
        if (queryDangerousSourceManagePageList.getConstructionStatuses() != null && queryDangerousSourceManagePageList.getConstructionStatuses().size() > 0) {
            LocalDate nowDate = LocalDate.now();
            switch (queryDangerousSourceManagePageList.getConstructionStatuses().toString()) {
                case "[-1]":
                    wrapper.ge("plan_construction_time", nowDate);
                    break;
                case "[0]":
                    wrapper.le("plan_construction_time", nowDate);
                    wrapper.ge("plan_end_time", nowDate);
                    break;
                case "[1]":
                    wrapper.le("plan_end_time", nowDate);
                    break;
                case "[0, 1]":
                case "[1, 0]":
                    wrapper.le("plan_construction_time", nowDate);      //正在施工和完成施工的，开工日期都比now小
                    break;
                case "[0, -1]":
                case "[-1, 0]":
                    wrapper.ge("plan_end_time", nowDate);       //未施工的和正在施工的，结束时间都比now大
                    break;
                case "[-1, 1]":
                case "[1, -1]":
                    wrapper.ge("plan_construction_time", nowDate);   //未施工的开始日期比now大
                    wrapper.le("plan_end_time", nowDate);            //施工完成的结束时间比now小
                    break;
                default:
                    break;
            }
        }

        Page<DangerousSourceManageEntity> resultReturn = this.getBaseMapper().selectPage(dangerousSourceManagePage, wrapper);

        /**
         * 添加搜索下的虽有危险源id
         */
        //private List<Long> dangerousSourceIds;

//        List<DangerousSourceManageEntity> searchReturn = new ArrayList<>();
//        searchReturn = searchValueList.stream().filter(n ->
//                queryDangerousSourceManageList.getProjectIds().contains(n.getProjectId())
//        ).collect(Collectors.toList());
//
//
//        List<DangerousSourceManageEntity> resultReturn = new ArrayList<>();
//
//        if (searchReturn.size() > 0) {
//            Collections.sort(searchReturn, new Comparator<DangerousSourceManageEntity>() {
//                public int compare(DangerousSourceManageEntity o1, DangerousSourceManageEntity o2) {
//                    return o2.getId().compareTo(o1.getId());
//                }
//            });
//
//            Long num = queryDangerousSourceManageList.getPageNum();
//            Long size = queryDangerousSourceManageList.getPageSize();
//            Long startIndex = (num - 1) * size;  //从数组的此项开始取
//            Long endIndex = num * size;          //取到此项
//            if (num * size >= searchReturn.size()) {
//                endIndex = Long.valueOf(searchReturn.size());
//            }
//            for (long i = startIndex; i < endIndex; i++) {
//                resultReturn.add(searchReturn.get((int) i));
//            }
//        }

        List<DangerousSourceManage> dangerousSourceManageList = dozerUtil.convertor(resultReturn.getRecords(), DangerousSourceManage.class);
        List<DangerousSourceManage> dangerousSourceManageListReturn = new ArrayList<>();

        for (DangerousSourceManage dangerousSourceManage : dangerousSourceManageList) {
            if (dangerousSourceManage.getLibraryId() > 0) {
                DangerousSourceLibrary dangerousSourceLibrary = dangerousSourceLibraryRepository.selectDangerousSourceLibraryById(dangerousSourceManage.getLibraryId());
                dangerousSourceManage.setDangerousSourceLibrary(dangerousSourceLibrary);
            }
        }

        for (DangerousSourceManage dangerousSourceManage : dangerousSourceManageList) {
            LocalDateTime now = LocalDateTime.now();
            LocalDateTime startTime = dangerousSourceManage.getPlanConstructionTime();
            LocalDateTime endTime = dangerousSourceManage.getPlanEndTime();


            if (now.isBefore(startTime)) {
                dangerousSourceManage.setConstructionStatus("-1");
            }
            if (!now.isBefore(startTime)&&!now.isAfter(endTime.plusDays(1))) {
                dangerousSourceManage.setConstructionStatus("0");
            }
            if(now.isAfter(endTime.plusDays(1))) {
                dangerousSourceManage.setConstructionStatus("1");
            }
            dangerousSourceManageListReturn.add(dangerousSourceManage);
        }

        if (dangerousSourceManageListReturn.size() > 0) {
            dangerousSourceManageListReturn.get(0).setDangerousSourceIds(new ArrayList<>());
            List<DangerousSourceManageEntity> resultReturnInfoIds = this.getBaseMapper().selectList(wrapper);
            for (DangerousSourceManageEntity dse : resultReturnInfoIds) {
                dangerousSourceManageListReturn.get(0).getDangerousSourceIds().add(dse.getId());
            }
        }

        dangerousSourceManagePageReturn.setRecords(dangerousSourceManageListReturn);
        dangerousSourceManagePageReturn.setTotal(resultReturn.getTotal());

        return dangerousSourceManagePageReturn;
    }

    @Override
    public List<DangerousSourceManage> selectDangerousSourceList(QueryDangerousSourceList queryDangerousSourceList) {
        LambdaQueryWrapper<DangerousSourceManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        if (queryDangerousSourceList.getId() != null) {
            DangerousSourceManageEntity dangerousSourceManageEntity = dangerousSourceManageMapper.selectById(queryDangerousSourceList.getId());
        }
        List<Long> projectTokenList = authorityUtil.getDataScope().getOrDefault("project", new ArrayList<>());
        List<Long> projectIds = queryDangerousSourceList.getProjectIds();
        if (projectIds != null && projectIds.size() > 0) {
            projectIds.retainAll(projectTokenList);
            lambdaQueryWrapper.in(DangerousSourceManageEntity::getProjectId, projectIds);
        } else {
            lambdaQueryWrapper.in(DangerousSourceManageEntity::getProjectId, projectTokenList);
        }
        if (queryDangerousSourceList.getConstructionUnit() != null && queryDangerousSourceList.getConstructionUnit().length() > 0) {
            lambdaQueryWrapper.like(DangerousSourceManageEntity::getConstructionUnit, queryDangerousSourceList.getConstructionUnit());
        }
        if (queryDangerousSourceList.getEngineeringCategory() != null && queryDangerousSourceList.getEngineeringCategory().length() > 0) {
            List<Long> longList = dangerousSourceLibraryRepository.selectDangerousSourceLibraryByEngineeringCategory(queryDangerousSourceList.getEngineeringCategory());
            lambdaQueryWrapper.in(DangerousSourceManageEntity::getLibraryId, longList);
        }
        if (queryDangerousSourceList.getUnitEngineering() != null && queryDangerousSourceList.getUnitEngineering().length() > 0) {
            lambdaQueryWrapper.like(DangerousSourceManageEntity::getUnitEngineering, queryDangerousSourceList.getUnitEngineering());
        }
        //开始时间段
        if (queryDangerousSourceList.getPlanConstructionTime() != null && queryDangerousSourceList.getPlanConstructionTime().length() > 0) {
            String[] strArr = queryDangerousSourceList.getPlanConstructionTime().split(",");
            LocalDateTime startTime0 = LocalDateTime.parse(strArr[0].toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime startTime1 = LocalDateTime.parse(strArr[1].toString(), DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            lambdaQueryWrapper.between(DangerousSourceManageEntity::getPlanConstructionTime, startTime0, startTime1);
        }
        //结束时间段
        if (queryDangerousSourceList.getPlanEndTime() != null && queryDangerousSourceList.getPlanEndTime().length() > 0) {
            String[] strArr = queryDangerousSourceList.getPlanEndTime().split(",");
            LocalDateTime startTime0 = LocalDateTime.parse(strArr[0], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            LocalDateTime startTime1 = LocalDateTime.parse(strArr[1], DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"));
            lambdaQueryWrapper.between(DangerousSourceManageEntity::getPlanEndTime, startTime0, startTime1);
        }
        if (queryDangerousSourceList.getKeyHazards() != null && queryDangerousSourceList.getKeyHazards().length() > 0) {
            List<Long> longList = dangerousSourceLibraryRepository.selectDangerousSourceLibraryByKeyHazards(queryDangerousSourceList.getKeyHazards());
            if (longList.size() > 0) {
                lambdaQueryWrapper.in(DangerousSourceManageEntity::getLibraryId, longList);
            }
        }
        if (queryDangerousSourceList.getConstructionStatus() != null && queryDangerousSourceList.getConstructionStatus().length() > 0) {
            LocalDate nowDate = LocalDate.now();
            switch (queryDangerousSourceList.getConstructionStatus()) {
                case "-1":
                    lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanConstructionTime, nowDate);
                    break;
                case "0":
                    lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanConstructionTime, nowDate);
                    lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanEndTime, nowDate);
                    break;
                case "1":
                    lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanEndTime, nowDate);
                    break;
                default:
                    break;
            }
        }
        if (queryDangerousSourceList.getConstructionStatuses() != null && queryDangerousSourceList.getConstructionStatuses().size() > 0) {
            LocalDate nowDate = LocalDate.now();
            switch (queryDangerousSourceList.getConstructionStatuses().toString()) {
                case "[-1]":
                    lambdaQueryWrapper.ge(DangerousSourceManageEntity::getConstructionUnit, nowDate);
                    break;
                case "[0]":
                    lambdaQueryWrapper.le(DangerousSourceManageEntity::getConstructionUnit, nowDate);
                    lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanEndTime, nowDate);
                    break;
                case "[1]":
                    lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanEndTime, nowDate);
                    break;
                case "[0, 1]":
                case "[1, 0]":
                    lambdaQueryWrapper.le(DangerousSourceManageEntity::getConstructionUnit, nowDate);      //正在施工和完成施工的，开工日期都比now小
                    break;
                case "[0, -1]":
                case "[-1, 0]":
                    lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanEndTime, nowDate);       //未施工的和正在施工的，结束时间都比now大
                    break;
                case "[-1, 1]":
                case "[1, -1]":
                    lambdaQueryWrapper.ge(DangerousSourceManageEntity::getConstructionUnit, nowDate);   //未施工的开始日期比now大
                    lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanEndTime, nowDate);            //施工完成的结束时间比now小
                    break;
                default:
                    break;
            }
        }

        List<DangerousSourceManageEntity> dangerousSourceManageEntityList = this.getBaseMapper().selectList(lambdaQueryWrapper);
        List<DangerousSourceManage> dangerousSourceManageList = dozerUtil.convertor(dangerousSourceManageEntityList, DangerousSourceManage.class);
        for (DangerousSourceManage dangerousSourceManage : dangerousSourceManageList) {
            if (dangerousSourceManage.getLibraryId() > 0) {
                DangerousSourceLibrary dangerousSourceLibrary = dangerousSourceLibraryRepository.selectDangerousSourceLibraryById(dangerousSourceManage.getLibraryId());
                dangerousSourceManage.setDangerousSourceLibrary(dangerousSourceLibrary);
            }
        }
        if (dangerousSourceManageList.size() > 0) {
            dangerousSourceManageList.get(0).setDangerousSourceIds(new ArrayList<>());
            for (DangerousSourceManageEntity dangerousSourceManageEntity : dangerousSourceManageEntityList) {
                dangerousSourceManageList.get(0).getDangerousSourceIds().add(dangerousSourceManageEntity.getId());
            }
        }
        return dangerousSourceManageList;
    }

    @Override
    public List<DangerousSourceManage> selectDangerousSourceListByDangerousIds(List<Long> dangerousSourceManageIds) {
        List<DangerousSourceManage> dangerousSourceManageList = new ArrayList<>();
        QueryWrapper<DangerousSourceManageEntity> wrapper = new QueryWrapper<>();
        wrapper.in("id", dangerousSourceManageIds);

        List<DangerousSourceManageEntity> dangerousSourceManageEntityList = this.getBaseMapper().selectList(wrapper);
        if (dangerousSourceManageEntityList == null) {
            return null;
        }

        //获取项目信息
        ProjectBasicResponse projectBasicResponse = constructionProjectRemoteApiService.queryProjectBasicView(dangerousSourceManageEntityList.get(0).getProjectId());

        List<DangerousSourceManage> dangerousSourceManageListReturn = new ArrayList<>();
        dangerousSourceManageList = dozerUtil.convertor(dangerousSourceManageEntityList, DangerousSourceManage.class);
        for (DangerousSourceManage dangerousSourceManage : dangerousSourceManageList) {
            DangerousSourceLibrary dangerousSourceLibrary = dozerUtil.convertor(dangerousSourceLibraryRepository.selectDangerousSourceLibraryById(dangerousSourceManage.getLibraryId()), DangerousSourceLibrary.class);
            dangerousSourceManage.setDangerousSourceLibrary(dangerousSourceLibrary);
            dangerousSourceManage.setProjectManager(projectBasicResponse.getProjectManager());
            dangerousSourceManage.setMobile(projectBasicResponse.getMobile());
            dangerousSourceManage.setProjectAddress(projectBasicResponse.getProjectAddress());

            dangerousSourceManageListReturn.add(dangerousSourceManage);
        }

        return dangerousSourceManageListReturn;
    }

    @Override
    public Page<DangerousSourceManage> selectMobileDangerousSourceList(MobileQueryDangerousSourceManageList queryDangerousSourceManageList) {
        Page<DangerousSourceManage> dangerousSourceManagePage = new Page<>(queryDangerousSourceManageList.getPageNum(), queryDangerousSourceManageList.getPageSize());
        QueryWrapper<DangerousSourceManageEntity> wrapper = new QueryWrapper<>();
        if (queryDangerousSourceManageList.getProjectIds().size() > 0) {
            wrapper.in("project_id", queryDangerousSourceManageList.getProjectIds());
        }

        if (queryDangerousSourceManageList.getKeyHazardsOrEngineeringCategory() != null && String.valueOf(queryDangerousSourceManageList.getKeyHazardsOrEngineeringCategory()).length() > 0) {
            List<Long> longList = dangerousSourceLibraryRepository.selectDangerousSourceLibraryByEngineeringCategoryAndKeyHazards(queryDangerousSourceManageList.getKeyHazardsOrEngineeringCategory());
            if (longList.size() > 0) {
                wrapper.in("library_id", longList);
            } else {
                longList.add(Long.valueOf(0));
                wrapper.in("library_id", longList);
            }
        }

        List<DangerousSourceManageEntity> searchValueList = this.getBaseMapper().selectList(wrapper);

        List<DangerousSourceManageEntity> searchReturn = new ArrayList<>();
        searchReturn = searchValueList.stream().filter(n ->
                queryDangerousSourceManageList.getProjectIds().contains(n.getProjectId())
        ).collect(Collectors.toList());

        LocalDateTime nowDate = LocalDateTime.now();
        List<DangerousSourceManageEntity> searchStatusReturnResult = new ArrayList<>();
        if (queryDangerousSourceManageList.getConstructionStatus() != null && queryDangerousSourceManageList.getConstructionStatus().size() > 0) {
            for (String status : queryDangerousSourceManageList.getConstructionStatus()) {
                switch (status) {
                    case "-1":
                        searchStatusReturnResult.addAll(searchReturn.stream().filter(n ->
                                nowDate.isBefore((n.getPlanConstructionTime().getDayOfMonth() == nowDate.getDayOfMonth() ?
                                        n.getPlanConstructionTime().plusDays(1) : n.getPlanConstructionTime()))
                        ).collect(Collectors.toList()));
                        break;
                    case "0":
                        searchStatusReturnResult.addAll(searchReturn.stream().filter(n ->
                                nowDate.isAfter((n.getPlanConstructionTime().getDayOfMonth() == nowDate.getDayOfMonth() ?
                                        n.getPlanConstructionTime().plusDays(1) : n.getPlanConstructionTime())) &&
                                        nowDate.isBefore((n.getPlanEndTime().getDayOfMonth() == nowDate.getDayOfMonth() ?
                                                n.getPlanEndTime().plusDays(1) : n.getPlanEndTime()))
                        ).collect(Collectors.toList()));
                        break;
                    case "1":
                        searchStatusReturnResult.addAll(searchReturn.stream().filter(n ->
                                nowDate.isAfter((n.getPlanEndTime().getDayOfMonth() == nowDate.getDayOfMonth() ?
                                        n.getPlanEndTime().plusDays(1) : n.getPlanEndTime()))
                        ).collect(Collectors.toList()));
                        break;
                    default:
                        break;
                }
            }
        } else {
            searchStatusReturnResult = searchReturn;
        }

        //去重
        List<DangerousSourceManageEntity> searchStatusReturn = new ArrayList<>();
        for (DangerousSourceManageEntity d : searchStatusReturnResult) {
            if (searchStatusReturn.stream().noneMatch(n ->
                    Objects.equals(n.getId(), d.getId()))) {
                searchStatusReturn.add(d);
            }
        }

        List<DangerousSourceManageEntity> resultReturn = new ArrayList<>();

        if (searchStatusReturn.size() > 0) {
            searchStatusReturn.sort(new Comparator<DangerousSourceManageEntity>() {
                public int compare(DangerousSourceManageEntity o1, DangerousSourceManageEntity o2) {
                    return o2.getId().compareTo(o1.getId());
                }
            });

            Long num = queryDangerousSourceManageList.getPageNum();
            Long size = queryDangerousSourceManageList.getPageSize();
            long startIndex = (num - 1) * size;  //从数组的此项开始取
            long endIndex = num * size;          //取到此项
            if (num * size >= searchStatusReturn.size()) {
                endIndex = (long) searchStatusReturn.size();
            }
            for (long i = startIndex; i < endIndex; i++) {
                resultReturn.add(searchStatusReturn.get((int) i));
            }
        }

        List<DangerousSourceManage> dangerousSourceManageList = dozerUtil.convertor(resultReturn, DangerousSourceManage.class);
        for (DangerousSourceManage dangerousSourceManage : dangerousSourceManageList) {
            if (dangerousSourceManage.getLibraryId() > 0) {
                DangerousSourceLibrary dangerousSourceLibrary = dangerousSourceLibraryRepository.selectDangerousSourceLibraryById(dangerousSourceManage.getLibraryId());
                dangerousSourceManage.setDangerousSourceLibrary(dangerousSourceLibrary);
            }

            //判断是不是同一天
            LocalDateTime startTime = dangerousSourceManage.getPlanConstructionTime();
            LocalDateTime endTime = dangerousSourceManage.getPlanEndTime();

            if (nowDate.getDayOfMonth() == dangerousSourceManage.getPlanConstructionTime().getDayOfMonth()) {
                nowDate.plusDays(1);
            }
            if (nowDate.getDayOfMonth() == dangerousSourceManage.getPlanEndTime().getDayOfMonth()) {
                endTime.plusDays(1);
            }

//            if (nowDate.isBefore(startTime)) {
//                dangerousSourceManage.setConstructionStatus("-1");
//            } else if (nowDate.isAfter(startTime) && nowDate.isBefore(endTime)) {
//                dangerousSourceManage.setConstructionStatus("0");
//            } else if (nowDate.isAfter(endTime)) {
//                dangerousSourceManage.setConstructionStatus("1");
//            }

            if (nowDate.isBefore(startTime)) {
                dangerousSourceManage.setConstructionStatus("-1");
            }
            if (!nowDate.isBefore(startTime)&&!nowDate.isAfter(endTime.plusDays(1))) {
                dangerousSourceManage.setConstructionStatus("0");
            }
            if(nowDate.isAfter(endTime.plusDays(1))) {
                dangerousSourceManage.setConstructionStatus("1");
            }
        }

        dangerousSourceManagePage.setRecords(dangerousSourceManageList);
        dangerousSourceManagePage.setTotal(searchStatusReturn.size());

        return dangerousSourceManagePage;
    }

    @Override
    public List<DangerousSourceManageEntity> getProjectWithDangerSourceList(DangerSourceListRequest dangerSourceListRequest) {
        List<Long> projectIds = authorityUtil.getDataScope().getOrDefault(ACCESS_PROJECT, new ArrayList<>());
        if (projectIds.isEmpty()) {
            return new ArrayList<>();
        }
        LambdaQueryWrapper<DangerousSourceManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DangerousSourceManageEntity::getProjectId, projectIds);
        lambdaQueryWrapper.in(ObjectUtils.isNotNull(dangerSourceListRequest.getProjectIds()), DangerousSourceManageEntity::getProjectId, dangerSourceListRequest.getProjectIds());
        if (StringUtils.isNotBlank(dangerSourceListRequest.getDayTime())) {
            lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanConstructionTime, dangerSourceListRequest.getDayTime())
                    .ge(DangerousSourceManageEntity::getPlanEndTime, dangerSourceListRequest.getDayTime());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanConstructionTimeStart())){
            lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanConstructionTime,dangerSourceListRequest.getPlanConstructionTimeStart().toLocalDate());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanConstructionTimeEnd())){
            lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanConstructionTime,dangerSourceListRequest.getPlanConstructionTimeEnd().toLocalDate());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanEndTimeStart())){
            lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanEndTime,dangerSourceListRequest.getPlanEndTimeStart().minusDays(1).toLocalDate());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanEndTimeEnd())){
            lambdaQueryWrapper.le(ObjectUtils.isNotNull(),DangerousSourceManageEntity::getPlanEndTime,dangerSourceListRequest.getPlanEndTimeEnd().minusDays(1).toLocalDate());
        }
        return dangerousSourceManageMapper.selectList(lambdaQueryWrapper);
    }

    @Override
    public Integer getProjectWithDangerSourceCount(DangerSourceListRequest dangerSourceListRequest) {
        List<Long> projectIds = authorityUtil.getDataScope().getOrDefault(ACCESS_PROJECT, new ArrayList<>());
        if (projectIds.isEmpty()) {
            return 0;
        }
        LambdaQueryWrapper<DangerousSourceManageEntity> lambdaQueryWrapper = new LambdaQueryWrapper<>();
        lambdaQueryWrapper.in(DangerousSourceManageEntity::getProjectId, projectIds);
        lambdaQueryWrapper.in(ObjectUtils.isNotNull(dangerSourceListRequest.getProjectIds()), DangerousSourceManageEntity::getProjectId, dangerSourceListRequest.getProjectIds());
        if (StringUtils.isNotBlank(dangerSourceListRequest.getDayTime())) {
            lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanConstructionTime, dangerSourceListRequest.getDayTime())
                    .ge(DangerousSourceManageEntity::getPlanEndTime, dangerSourceListRequest.getDayTime());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanConstructionTimeStart())){
            lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanConstructionTime,dangerSourceListRequest.getPlanConstructionTimeStart().toLocalDate());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanConstructionTimeEnd())){
            lambdaQueryWrapper.le(DangerousSourceManageEntity::getPlanConstructionTime,dangerSourceListRequest.getPlanConstructionTimeEnd().toLocalDate());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanEndTimeStart())){
            lambdaQueryWrapper.ge(DangerousSourceManageEntity::getPlanEndTime,dangerSourceListRequest.getPlanEndTimeStart().minusDays(1).toLocalDate());
        }
        if(VerifyHelper.isAvailable(dangerSourceListRequest.getPlanEndTimeEnd())){
            lambdaQueryWrapper.le(ObjectUtils.isNotNull(),DangerousSourceManageEntity::getPlanEndTime,dangerSourceListRequest.getPlanEndTimeEnd().minusDays(1).toLocalDate());
        }
        return dangerousSourceManageMapper.selectCount(lambdaQueryWrapper);
    }

    @Override
    public Integer getDangerSourceCountByTimeLine(TimeLine timeLine) {
        LambdaQueryWrapper<DangerousSourceManageEntity> wrapper = new LambdaQueryWrapper<>();
        List<Long> projectIds = authorityUtil.getDataScope().getOrDefault(ACCESS_PROJECT, new ArrayList<>());
        if (projectIds.isEmpty()) {
            return 0;
        }
        wrapper.in(DangerousSourceManageEntity::getProjectId,projectIds);
        //因为时分秒默认00:00:00的原因，需设置结束日期天数加1
        timeLine.setEndTime(timeLine.getEndTime().plusDays(1L));

        //and not ( mmh.plan_construction_time <'2022-11-01 00:00:00' and mmh.plan_end_time <'2022-11-01 00:00:00')
        wrapper.and(it->it.not(
                it1->it1.lt(DangerousSourceManageEntity::getPlanConstructionTime,timeLine.getStartTime())
                        .and(it2->it2.lt(DangerousSourceManageEntity::getPlanEndTime,timeLine.getStartTime()))
        ));
        //and not (mmh.plan_construction_time >='2022-12-01 00:00:00' and mmh.plan_end_time>'2022-12-01 00:00:00')
        wrapper.and(it->it.not(
                it1->it1.ge(DangerousSourceManageEntity::getPlanConstructionTime,timeLine.getEndTime())
                        .and(it2 -> it2.gt(DangerousSourceManageEntity::getPlanEndTime,timeLine.getEndTime()))
        ));
        return dangerousSourceManageMapper.selectCount(wrapper);
    }


}